package 线程池;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceDemo {

    public static void main(String[] args) {
        //固定大小的线程池
        ExecutorService fixed = Executors.newFixedThreadPool(2);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("线程:" + Thread.currentThread().getName());
            }
        };
        fixed.submit(runnable);
        fixed.execute(runnable);
        fixed.execute(runnable);
        fixed.execute(runnable);
        //单线程池
        ExecutorService single = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            single.execute(() -> {
                System.out.println(index);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                }
            });
        }
        //缓存的线程池
        ExecutorService cached = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            cached.execute(() -> {
                System.out.println("线程:" + Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                }
            });
        }
        //计划任务的线程池
        ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(4);
        System.out.println("添加任务,时间:" + new Date());

        scheduled.schedule(() -> {
            System.out.println("任务被执行,时间:" + new Date());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
        }, 1, TimeUnit.SECONDS);
    }
}